package beautiful.butterfly.drds.binlog.zookeeper;

import beautiful.butterfly.drds.binlog.operation.OpeationEvent;
import beautiful.butterfly.drds.binlog.operation.OpeationEventQueue;
import beautiful.butterfly.drds.binlog.operation.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

@Slf4j
public class RunningListener
{

    private static RunningListener instance;
    private PathChildrenCacheListener listener;
    ///

    private RunningListener(PathChildrenCacheListener l)
    {
        listener = l;
    }

    public static RunningListener getInstance()
    {
        if (null == instance)
        {
            synchronized (RunningListener.class)
            {
                if (null == instance)
                {
                    PathChildrenCacheListener listener = new PathChildrenCacheListener()
                    {
                        @Override
                        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
                        {
                            // 正式处理业务
                            switch (event.getType())
                            {
                                case CHILD_REMOVED:
                                    String currentPath = event.getData().getPath();
                                    log.info(this + "running/current removed," + currentPath);
                                    OpeationEvent operationEvent = new OpeationEvent(event, OperationType.running_delete);
                                    OpeationEventQueue.addObject(operationEvent);
                                    break;
                                default:
                                    break;
                            }
                        }
                    };

                    instance = new RunningListener(listener);
                }
            }
        }
        return instance;
    }

    public PathChildrenCacheListener getListener()
    {
        return listener;
    }
}
